package gulimall.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import gulimall.config.ElasticSearchConfig;
import gulimall.constant.EsConstant;
import gulimall.domain.bo.SearchParamBo;
import gulimall.domain.vo.SearchResultVo;
import gulimall.service.SearchService;
import gulimall.to.es.SkuEsModel;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/10 12:59
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Resource
    private RestHighLevelClient client;

    /**
     * 检索方法
     *
     * @param paramBo 检索参数对象
     * @return
     */
    @Override
    public SearchResultVo search(SearchParamBo paramBo) {
        SearchResultVo searchResultVo = null;

        SearchRequest searchRequest = this.buildSearchRequest(paramBo);
        try {
            SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

            searchResultVo = this.buildSearchResult(searchResponse, paramBo);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return searchResultVo;
    }

    /**
     * 构建检索请求(根据Kibana写好的DSL语句构建)
     * 模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存）、排序、分页、高亮、聚合分析
     */
    private SearchRequest buildSearchRequest(SearchParamBo paramBo) {
        SearchRequest searchRequest = new SearchRequest(EsConstant.PRODUCT_INDEX);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建DSL语句

        //1.bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must 搜索框关键字模糊查询
        if (StringUtils.isNotBlank(paramBo.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", paramBo.getKeyword()));
        }
        //1.2.1 filter catelogId 三级分类id查询
        if (paramBo.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catelogId", paramBo.getCatalog3Id()));
        }
        //1.2.2 filter brandId 根据品牌id查询
        List<Long> brandId = paramBo.getBrandId();
        if (brandId != null && brandId.size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", brandId));
        }
        //1.2.3 filter hasStock 是否有库存
        if (paramBo.getHasStock() != null) {
            boolean hasStock = paramBo.getHasStock() > 0;
            boolQuery.filter(QueryBuilders.termQuery("hasStock", hasStock));
        }
        //1.2.4 filter range skuPrice 价格区间
        String skuPrice = paramBo.getSkuPrice();
        if (StringUtils.isNotBlank(skuPrice)) {
            String[] prices = skuPrice.split("_");
            if (prices.length == 2) {
                boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").gte(prices[0]).lte(prices[1]));
            } else if (prices.length == 1) {
                if (skuPrice.startsWith("_")) {
                    boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").lte(prices[0]));
                }
                if (skuPrice.endsWith("_")) {
                    boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").gte(prices[0]));
                }
            }
        }
        //1.2.5 filter attrs 根据属性id，属性值查询
        List<String> attrs = paramBo.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            //获取attrId集合
            List<String> attrId = attrs.stream().map(s -> s.split("_")[0]).collect(Collectors.toList());

            //获取attrValue集合
            List<String> attrValue = new ArrayList<>();
            attrs.forEach(s -> {
                String attrString = s.split("_")[1];
                String[] split = attrString.split(":");
                attrValue.addAll(Arrays.asList(split));
            });

            //构建bool-query
            BoolQueryBuilder query = QueryBuilders.boolQuery();

            //构建查询attrId
            query.must(QueryBuilders.termsQuery("attrs.attrId", attrId));

            //构建查询attrValue
            query.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));

            boolQuery.filter(QueryBuilders.nestedQuery("attrs", query, ScoreMode.None));
        }
        sourceBuilder.query(boolQuery);

        //2.sort 排序
        String sortString = paramBo.getSort();
        if (StringUtils.isNotBlank(sortString)) {
            String[] sortStrs = sortString.split("_");
            String AscDesc = sortStrs[1];
            if (AscDesc.equalsIgnoreCase("desc")) {
                sourceBuilder.sort(sortStrs[0], SortOrder.DESC);
            } else {
                sourceBuilder.sort(sortStrs[0], SortOrder.ASC);
            }
        }

        //3.from size 分页
        if (paramBo.getPageNum() != null) {
            sourceBuilder.from((paramBo.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        } else {
            sourceBuilder.from(1);
        }
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //4.highlight  检索关键字高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<b style=color:red>");
        highlightBuilder.postTags("</b>");
        sourceBuilder.highlighter(highlightBuilder);

        //5.aggs 聚合
        //5.1 brand_agg
        //branId聚合  brandName子聚合，brandImg子聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId");
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName"));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg"));

        sourceBuilder.aggregation(brand_agg);

        //5.2catelog_agg
        //catelogId聚合  catelogName子聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg").field("catelogId");
        //❗️注意这里有坑：ElasticSearch中的字段创建了两个：catelogName和catalogName(用这个)
        catelog_agg.subAggregation(AggregationBuilders.terms("catelog_name_agg").field("catelogName"));

        sourceBuilder.aggregation(catelog_agg);

        //5.3 attr_agg
        //attr_id_agg聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //attr_name_agg子聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName"));
        //attr_value_agg子聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));

        NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("attr_agg", "attrs").subAggregation(attr_id_agg);

        sourceBuilder.aggregation(nestedAggregationBuilder);

        searchRequest.source(sourceBuilder);

        return searchRequest;
    }

    /**
     * 构建检索结果
     */
    private SearchResultVo buildSearchResult(SearchResponse searchResponse, SearchParamBo paramBo) {
        SearchResultVo searchResultVo = new SearchResultVo();

        //检索结果
        SearchHits hits = searchResponse.getHits();
        //聚合
        Aggregations aggregations = searchResponse.getAggregations();

        //查询到的总记录数
        TotalHits totalHits = hits.getTotalHits();
        //设置分页相关信息
        //1.total
        long total = totalHits.value;
        searchResultVo.setTotal(total);

        //2.pageNum
        Integer pageNum = paramBo.getPageNum();
        searchResultVo.setPageNum(pageNum);
        //3.totalPages
        //totalPages(总页数)=[(total(总记录数)-1) / pageSize(每页显示数目)] +1
        searchResultVo.setTotalPages(Math.toIntExact(((total - 1) / EsConstant.PRODUCT_PAGESIZE) + 1));

        List<Integer> pageNavs = new ArrayList<>();
        for (Integer i = 1; i <= searchResultVo.getTotalPages(); i++) {
            pageNavs.add(i);
        }
        searchResultVo.setPageNavs(pageNavs);//设置所有导航页，便于在前端页面做分页显示

        //设置商品信息(SkuModel)
        //4.products
        List<SkuEsModel> products = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            String sourceAsString = hit.getSourceAsString();

            ObjectMapper mapper = new ObjectMapper();
            try {
                SkuEsModel skuEsModel = mapper.readValue(sourceAsString, SkuEsModel.class);

                //设置skuTitle(高亮显示)
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                if (skuTitle != null) {
                    String skuTitleString = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitleString);
                }

                products.add(skuEsModel);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        searchResultVo.setProducts(products);

        //5.brands
        //根据聚合获取品牌相关信息
        List<SearchResultVo.BrandVo> brandVos = new ArrayList<>();
        Terms brandAgg = aggregations.get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            //获取brandId
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);

            //获取brandName
            Terms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            //获取品牌图片
            Terms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        searchResultVo.setBrands(brandVos);

        //6.catalogs
        List<SearchResultVo.CatalogVo> catalogVos = new ArrayList<>();
        Terms catelog_agg = aggregations.get("catelog_agg");
        for (Terms.Bucket bucket : catelog_agg.getBuckets()) {
            SearchResultVo.CatalogVo catalogVo = new SearchResultVo.CatalogVo();

            //获取catalogId
            long catalogId = bucket.getKeyAsNumber().longValue();
            catalogVo.setCatalogId(catalogId);

            //获取catalogName
            Terms catelog_name_agg = bucket.getAggregations().get("catelog_name_agg");
            String catalogName = catelog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogVos.add(catalogVo);
        }
        searchResultVo.setCatalogs(catalogVos);

        //7.attrs
        List<SearchResultVo.AttrVo> attrs = new ArrayList<>();
        //nested使用ParsedNested作为返回值类型
        ParsedNested attr_agg = aggregations.get("attr_agg");
        Terms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();

            //获取attrId
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            //获取属性名
            Terms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            //获取属性值
            Terms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);

            attrs.add(attrVo);
        }
        searchResultVo.setAttrs(attrs);

        return searchResultVo;

    }
}
